import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'

// 开发环境8000
if (process.env.NODE_ENV === "development") {
    // console.log('开发环境');
    Vue.prototype.$pre = 'http://localhost:3000'
    // console.log(Vue.prototype.$pre);
    // console.log(http.defaults);
}

// 生产环境
if (process.env.NODE_ENV === "production") {
    console.log('生产环境');
    Vue.prototype.$pre = ''
}

// 请求拦截器
axios.interceptors.request.use((config) => {
    // console.log(config);
    console.log("===请求拦截器开始===");
    console.log(config);
    console.log("===请求拦截器结束===");
    console.log(config);
    if(config.url=='/api/addresslist'||config.url=='/api/orderadd'){
        config.headers.authorization = JSON.parse(sessionStorage.getItem("user")).token
        config.headers.contentType="application/json"
    }
    return config
})

// 响应拦截器
axios.interceptors.response.use((res) => {
    console.log("===响应拦截器开始===");
    console.log(res);
    console.log("===响应拦截器结束==="); 
    return res
})

// 二次封装
export let get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

export let post = (url, params, flag = false) => {
    let data = null
    if (flag) {
        data = new FormData()
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        data = qs.stringify(params)
    }
    return new Promise((resolve, reject) => {
        axios.post(url, data).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}